﻿using System;
using System.Drawing;
using System.Windows.Forms;
using AMM.UserControls;

namespace AMM.Forms {
    public partial class FrmEdit : FrmRootBase {

        private bool _isFromClosing;

        #region Edit event

        public delegate bool EditEventHandler(object sender, EditArgs e);
        public event EditEventHandler Edit;
        public bool OnEdit(object sender, EditArgs e) {
            if (this.Edit != null) {
                return this.Edit(sender, e);
            }
            return false;
        }

        public class EditArgs : EventArgs {
            public object EditModel { get; set; }
        }

        #endregion

        public FrmEdit() {
            this.InitializeComponent();
        }

        private BaseEditControl GetEditControl() {
            BaseEditControl editControl = new BaseEditControl();
            foreach (Control c in this.Controls) {
                if (c is BaseEditControl) {
                    editControl = (BaseEditControl)c;
                    break;
                }
            }
            return editControl;
        }

        private void btnSave_Click(object sender, EventArgs e) {
            if (!this.validatorForEdit.Validate()) {
                this.ShowInfo("请正确填写所需的数据！");
                return;
            }
            BaseEditControl editControl = this.GetEditControl();
            bool flag = this.OnEdit(this, new EditArgs() {
                EditModel = editControl.BaseEditModel
            });

            this._isFromClosing = true;
        }

        private void btnClose_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void FrmEdit_ControlAdded(object sender, ControlEventArgs e) {
            BaseEditControl editControl = this.GetEditControl();
            this.Bounds = editControl.Bounds;
            editControl.Location = new Point(0, 10);
            this.Height += this.pnlBtn.Height * 2 + 30;
            this.Width = (this.Width <= this.pnlBtn.Width ? this.pnlBtn.Width : this.Width) + 20;
            this.pnlBtn.Location = new Point((editControl.Width - this.pnlBtn.Width) / 2, editControl.Top + editControl.Height + 10);
        }

        private void FrmEdit_FormClosing(object sender, FormClosingEventArgs e) {
            e.Cancel = !this._isFromClosing && !(this.ShowQuestion("有操作未保存，直接退出吗？") == DialogResult.Yes);
        }
    }
}
